package com.ares.basic.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuezn on 2016/6/24.
 */
@Slf4j
public class DozerUtils {

    public static <T> List<T> map(final List source, final Class<T> destination) {
        List<T> desList = new ArrayList<>();
        if (CollectionUtils.isEmpty(source)) {
            return desList;
        }
        try {
            BeanCopier copier = BeanCopier.create(source.getClass(), destination, false);
            for (Object src : source) {
                T res = destination.newInstance();
                copier.copy(src, res, null);
                desList.add(res);
            }
        } catch (Exception e) {
            log.error("bean copy 失败");
        }
        return desList;
    }

    public static <T> T map(Object src, final Class<T> destination) {
        if (src == null) {
            return null;
        }
        T des = null;
        try {
            BeanCopier copier = BeanCopier.create(src.getClass(), destination, false);
            T res = destination.newInstance();
            copier.copy(src, res, null);
        } catch (Exception e) {
            log.error("bean copy 失败");
        }
        return des;
    }
}
